package com.ycsj.goldmedalnewconcept.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.adapter.PopLvAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.UserinfoResp;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.RegionInfo;
import com.ycsj.goldmedalnewconcept.pickerview.dao.RegionDAO;
import com.ycsj.goldmedalnewconcept.pickerview.listener.OnDismissListener;
import com.ycsj.goldmedalnewconcept.pickerview.view.OptionsPickerView;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.utils.BitmapCompressor;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.ActionSheet;
import com.ycsj.goldmedalnewconcept.view.ActionSheet.MenuItemClickListener;
import com.ycsj.goldmedalnewconcept.R;

//创建学生
@SuppressLint("SimpleDateFormat")
public class CreatStudentActivity extends Activity implements OnClickListener,
		MenuItemClickListener {
	private ImageView img_back;
	OptionsPickerView pvOptions;
	protected static final int CHOOSE_PICTURE = 0;
	protected static final int TAKE_PICTURE = 1;
	private static final int CROP_SMALL_PICTURE = 2;
	protected static Uri tempUri;
	private int mWH = 360;// 单位dp
	private int requestCode;
	static ArrayList<RegionInfo> item1;
	static ArrayList<ArrayList<RegionInfo>> item2 = new ArrayList<ArrayList<RegionInfo>>();
	static ArrayList<ArrayList<ArrayList<RegionInfo>>> item3 = new ArrayList<ArrayList<ArrayList<RegionInfo>>>();
	Bitmap bitmap2headimg = null;
	
	private String birthday;
	private String address;
	private String sex;
	private String province;
	private String city;
	private String area;
	private String c;
	private String role;
	private Intent intent;
	private Intent mIntent;
	private String name;
	private String tel;
	private String nickname;
	private String headimg;
	private String school;
	private String grade;
	private String payment;
	private String isPic = "-1";
	private LinearLayout ll_loading;
	
	private HttpUtils httpUtils;
	private String url;
	private RequestParams params;
	private RequestParams params1;
	private String jpgName;

	private ActionSheet menuView;
	private ActionSheet menuView1;

	private ImageView iv_user_headimg;
	ArrayList<String> list = new ArrayList<String>();
	ArrayList<String> list2 = new ArrayList<String>();
	public int pro_position = 0;

	private RelativeLayout rl_user_icon;

	private RelativeLayout rl_user_name;

	private RelativeLayout rl_user_tel;

	private RelativeLayout rl_user_sex;

	private RelativeLayout rl_user_birthday;

	private RelativeLayout rl_user_address;

	private RelativeLayout rl_user_nickname; // 昵称
	private RelativeLayout rl_school; // 学校
	private RelativeLayout rl_grade; // 年级
	private RelativeLayout rl_status; // 缴费状态

	private TextView tv_user_name;
	private TextView tv_user_nickname;
	private TextView tv_grade;
	private TextView tv_school;
	private TextView tv_status;
	private TextView tv_upload;

	private TextView tv_user_tel;

	private TextView tv_user_sex;

	private TextView tv_user_birthday;

	private TextView tv_user_address;

	TimePickerView pvTime;
	
	
	
	// 弹框相关
	private View commonView;
	private PopupWindow popupWindow;
	private TextView tvTitle, tvCancel;
	private ListView lvCommon;
	private View viewTop;
	private PopLvAdapter popLvAdapter;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// System.out.println(System.currentTimeMillis());
			// 三级联动效果

			pvOptions.setPicker(item1, item2, item3, true);
			pvOptions.setCyclic(true, true, true);
			pvOptions.setSelectOptions(0, 0, 0);
			rl_user_address.setClickable(true);
		};
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_creatstudent);

		c = SPUtil.getString(CreatStudentActivity.this, "account", "");
		role = SPUtil.getString(CreatStudentActivity.this, "role", "");

		mIntent = new Intent();
		mIntent.setClass(CreatStudentActivity.this,
				UpdateStudentinfoActivity.class);
		initView();
		setOnListener();
	}

	private void initView() {
		rl_user_icon = (RelativeLayout) findViewById(R.id.rl_user_icon);
		rl_user_name = (RelativeLayout) findViewById(R.id.rl_user_name);
		rl_user_tel = (RelativeLayout) findViewById(R.id.rl_user_tel);
		rl_user_sex = (RelativeLayout) findViewById(R.id.rl_user_sex);
		rl_user_birthday = (RelativeLayout) findViewById(R.id.rl_user_birthday);
		rl_user_address = (RelativeLayout) findViewById(R.id.rl_user_address);

		rl_user_nickname = (RelativeLayout) findViewById(R.id.rl_user_nickname);
		rl_school = (RelativeLayout) findViewById(R.id.rl_school);
		rl_grade = (RelativeLayout) findViewById(R.id.rl_grade);
		rl_status = (RelativeLayout) findViewById(R.id.rl_status);
		tv_user_nickname = (TextView) findViewById(R.id.tv_user_nickname);
		tv_grade = (TextView) findViewById(R.id.tv_grade);
		tv_school = (TextView) findViewById(R.id.tv_school);
		tv_status = (TextView) findViewById(R.id.tv_status);
		tv_upload = (TextView) findViewById(R.id.tv_upload);

		tv_user_name = (TextView) findViewById(R.id.tv_user_name);
		tv_user_tel = (TextView) findViewById(R.id.tv_user_tel);
		tv_user_sex = (TextView) findViewById(R.id.tv_user_sex);
		tv_user_birthday = (TextView) findViewById(R.id.tv_user_birthday);
		tv_user_address = (TextView) findViewById(R.id.tv_user_address);
		iv_user_headimg = (ImageView) findViewById(R.id.iv_user_headimg);
		img_back = (ImageView) findViewById(R.id.img_back);
		
		ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
	}

	private void setOnListener() {

		img_back.setOnClickListener(this);

		rl_user_icon.setOnClickListener(this);
		rl_user_name.setOnClickListener(this);
		rl_user_tel.setOnClickListener(this);
		rl_user_sex.setOnClickListener(this);
		rl_user_birthday.setOnClickListener(this);
		rl_user_address.setOnClickListener(this);

		rl_user_nickname.setOnClickListener(this);
		rl_school.setOnClickListener(this);
		rl_grade.setOnClickListener(this);
		rl_status.setOnClickListener(this);
		tv_upload.setOnClickListener(this);

		// 时间选择器
		pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
		pvTime.setRange(2000, 2017);
		pvTime.setTime(new Date());
		pvTime.setCyclic(false);
		pvTime.setCancelable(true);
		// 时间选择后回调
		pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

			@Override
			public void onTimeSelect(Date date) {
				// updateUserinfo("生日", getTime(date));
				tv_user_birthday.setText(getTime(date));

			}
		});

		// 选项选择器
		pvOptions = new OptionsPickerView(this);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// System.out.println(System.currentTimeMillis());
				if (item1 != null && item2 != null && item3 != null) {
					handler.sendEmptyMessage(0x123);
					return;
				}
				item1 = (ArrayList<RegionInfo>) RegionDAO.getProvencesOrCity(1);
				for (RegionInfo regionInfo : item1) {
					item2.add((ArrayList<RegionInfo>) RegionDAO
							.getProvencesOrCityOnParent(regionInfo.getId()));

				}

				for (ArrayList<RegionInfo> arrayList : item2) {
					ArrayList<ArrayList<RegionInfo>> list2 = new ArrayList<ArrayList<RegionInfo>>();
					for (RegionInfo regionInfo : arrayList) {

						ArrayList<RegionInfo> q = (ArrayList<RegionInfo>) RegionDAO
								.getProvencesOrCityOnParent(regionInfo.getId());
						list2.add(q);

					}
					item3.add(list2);
				}

				handler.sendEmptyMessage(0x123);

			}
		}).start();
		// 设置选择的三级单位
		// pwOptions.setLabels("省", "市", "区");
		pvOptions.setTitle("选择城市");

		// 设置默认选中的三级项目
		// 监听确定选择按钮

		pvOptions
				.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

					@Override
					public void onOptionsSelect(int options1, int option2,
							int options3) {
						// 返回的分别是三个级别的选中位置
						String tx = item1.get(options1).getPickerViewText()
								+"-"+ item2.get(options1).get(option2)
										.getPickerViewText();
								
//						String tx = item1.get(options1).getPickerViewText()
//								+ item2.get(options1).get(option2)
//								.getPickerViewText()
//								+ item3.get(options1).get(option2)
//								.get(options3).getPickerViewText();
						
						province = item1.get(options1).getPickerViewText();
						city = item2.get(options1).get(option2)
								.getPickerViewText();
						area = item3.get(options1).get(option2).get(options3)
								.getPickerViewText();
						// updateUserinfo("所在地", tx);
						tv_user_address.setText(tx);
						
					}
				});
		
		pvOptions.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(Object o) {
				// TODO Auto-generated method stub
				rl_user_address.setClickable(true);
			}
		});
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_cancel:
			// 弹框的取消
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				commonView = null;
			}
			break;
		case R.id.img_back:
			finish();
			break;
		case R.id.rl_user_icon:
			showChoosePicDialog();
			break;
		case R.id.rl_user_name:
			requestCode = 3;
			mIntent.putExtra("title", "姓名");
			mIntent.putExtra("requestCode", 3);
			startActivityForResult(mIntent, requestCode);
			break;
		case R.id.rl_user_nickname:
			requestCode = 4;
			mIntent.putExtra("title", "昵称");
			mIntent.putExtra("requestCode", 4);
			startActivityForResult(mIntent, requestCode);
			break;
		case R.id.rl_school:
			requestCode = 6;
			mIntent.putExtra("title", "学校");
			mIntent.putExtra("requestCode", 6);
			startActivityForResult(mIntent, requestCode);
			break;
		case R.id.rl_grade:
//			requestCode = 7;
//			mIntent.putExtra("title", "年级");
//			mIntent.putExtra("requestCode", 7);
//			startActivityForResult(mIntent, requestCode);
			
			
			List<String> schools = new ArrayList<>();
			for (int i = 1; i < 10; i++) {
				schools.add(i + "");
			}
			showPic(schools);
			
			
			break;
		case R.id.rl_status:
			setTheme(R.style.ActionSheetStyleIOS7);
			showPayment();
			break;
		case R.id.rl_user_tel:
			requestCode = 5;
			mIntent.putExtra("title", "电话");
			mIntent.putExtra("requestCode", 5);
			startActivityForResult(mIntent, requestCode);
			break;
		case R.id.rl_user_sex:
			setTheme(R.style.ActionSheetStyleIOS7);
			showActionSheet();
			break;
		case R.id.rl_user_birthday:
			pvTime.show();
			break;
		case R.id.rl_user_address:
			pvOptions.show();
			rl_user_address.setClickable(false);
			break;
		case R.id.tv_upload://创建
			
			name = tv_user_name.getText().toString().trim();
			nickname = tv_user_nickname.getText().toString().trim();
			sex = tv_user_sex.getText().toString().trim();
			birthday = tv_user_birthday.getText().toString().trim();
			tel = tv_user_tel.getText().toString().trim();
			address = tv_user_address.getText().toString().trim();
			school = tv_school.getText().toString().trim();
			grade = tv_grade.getText().toString().trim();
			payment = tv_status.getText().toString().trim();

			if("".equals(name)){
				Toast.makeText(CreatStudentActivity.this, "请输入学生姓名", 0).show();
				return;
			}
			if("".equals(nickname)){
				Toast.makeText(CreatStudentActivity.this, "请输入学生昵称", 0).show();
				return;
			}
			if("".equals(sex)){
				Toast.makeText(CreatStudentActivity.this, "请选择学生性别", 0).show();
				return;
			}
			if("".equals(birthday)){
				Toast.makeText(CreatStudentActivity.this, "请选择学生生日", 0).show();
				return;
			}
			if("".equals(tel)){
				Toast.makeText(CreatStudentActivity.this, "请输入学生电话号码", 0).show();
				return;
			}
			if("".equals(address)){
				Toast.makeText(CreatStudentActivity.this, "请选择学生地址", 0).show();
				return;
			}
			if("".equals(school)){
				Toast.makeText(CreatStudentActivity.this, "请输入学生学校名", 0).show();
				return;
			}
			if("".equals(grade)){
				Toast.makeText(CreatStudentActivity.this, "请输入学生年级", 0).show();
				return;
			}
			if("".equals(payment)){
				Toast.makeText(CreatStudentActivity.this, "请选择学生缴费状态", 0).show();
				return;
			}
			if(!"1".equals(isPic)){
				Toast.makeText(CreatStudentActivity.this, "请选择学生头像", 0).show();
				return;
			}
			
			boolean isphone = isChinaPhoneLegal(tel);
			if(!isphone){
				Toast.makeText(getBaseContext(), "请输入正确的手机号码", 0).show();
				return;
			}
			
			upload();
//			tv_upload.setClickable(false);
			break;
		default:
			break;
		}
	}

	private void showPic( final List<String> contents) {
		// TODO Auto-generated method stub
		commonView = View.inflate(this, R.layout.pop_commonview, null);
		tvTitle = (TextView) commonView.findViewById(R.id.tv_title);
		viewTop = commonView.findViewById(R.id.view_top);
		lvCommon = (ListView) commonView.findViewById(R.id.lv);
		tvCancel = (TextView) commonView.findViewById(R.id.tv_cancel);
		tvCancel.setOnClickListener(this);
		tvTitle.setText("年级");
		
		popLvAdapter = new PopLvAdapter(this, contents,
				R.layout.lv_item_pop_common);
		lvCommon.setAdapter(popLvAdapter);
		
		// 设置条目点击事件
				lvCommon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView, View view,
							int i, long l) {
							// 年级
							tv_grade.setText(contents.get(i));
							if (popupWindow != null) {
								popupWindow.dismiss();
							}
					}
				});
		
		
		
		popupWindow = new PopupWindow(commonView,
				WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		backgroundAlpha(this, 0.3f);
		popupWindow.setAnimationStyle(R.style.pop_common_style);
		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
			@Override
			public void onDismiss() {
				backgroundAlpha(CreatStudentActivity.this, 1.0f);
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow = null;
					commonView = null;
				}
			}
		});
		popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM,
				0, 0);
		
		
	}

	/**
	 * 改变屏幕透明度 方法
	 *
	 * @param bgAlpha
	 */
	public void backgroundAlpha(Activity activity, float bgAlpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = bgAlpha;
		activity.getWindow().setAttributes(lp);
	}

	// 国内运营商手机号码
	public boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
//		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		String regExp = ("^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0-9])|(16[0-9]))\\d{8}$");
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	private void showPayment() {
		// TODO Auto-generated method stub
		menuView1 = new ActionSheet(this);
		menuView1.setCancelButtonTitle("cancel");// before add items
		menuView1.addItems("已缴", "未缴","自定义");
		menuView1.setItemClickListener(new MenuItemClickListener() {

			@Override
			public void onItemClick(int itemPosition) {
				if(itemPosition==2){
					requestCode = 8;
					mIntent.putExtra("title", "缴费状态");
					mIntent.putExtra("requestCode", 8);
					startActivityForResult(mIntent, requestCode);
//					startActivity(mIntent);
					Log.e("test", "Cancel");
				}else{
					tv_status.setText(menuView1
							.returnCancelButtonTitle(itemPosition));
					payment = menuView1.returnCancelButtonTitle(itemPosition);
				}
			}
		});
		menuView1.setCancelableOnTouchMenuOutside(true);
		menuView1.showMenu();
	}

	public void showActionSheet() {
		menuView = new ActionSheet(this);
		menuView.setCancelButtonTitle("cancel");// before add items
		menuView.addItems("男", "女");
		menuView.setItemClickListener(this);
		menuView.setCancelableOnTouchMenuOutside(true);
		menuView.showMenu();
	}

	@Override
	public void onItemClick(int itemPosition) {
		tv_user_sex.setText(menuView.returnCancelButtonTitle(itemPosition));
		sex = menuView.returnCancelButtonTitle(itemPosition);
	}

	public static String getTime(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(date);
	}


	protected void showChoosePicDialog() {
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"HHmmss");
		String format = dateFormat.format(date);
		jpgName = format;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("设置头像");
		String[] items = { "选择本地图片", "拍照" };
		builder.setNegativeButton("取消", null);
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case CHOOSE_PICTURE:
					Intent openAlbumIntent = new Intent(
							Intent.ACTION_GET_CONTENT);
					openAlbumIntent.setType("image/*");
					// Data = Uri.fromFile(new File(Environment
					// .getExternalStorageDirectory(), "image1.jpg"));
					startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
					break;

				case TAKE_PICTURE:
					Intent openCameraIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					tempUri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), "image.jpg"));
					openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
					startActivityForResult(openCameraIntent, TAKE_PICTURE);
					break;
				}
			}
		});
		builder.create().show();
	}



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 3:
				String name = data.getStringExtra("date");
				Log.e("testt", name);
				tv_user_name.setText(name);
				break;
			case 4:
				String nickname = data.getStringExtra("date");
				Log.e("testt", nickname);
				tv_user_nickname.setText(nickname);
				break;
			case 5:
				String tel = data.getStringExtra("date");
				Log.e("testt", tel);
				tv_user_tel.setText(tel);
				break;

			case 6:
				String school = data.getStringExtra("date");
				tv_school.setText(school);
				break;

			case 7:
				String grade = data.getStringExtra("date");
				tv_grade.setText(grade);
				break;
			case 8:
				String status = data.getStringExtra("date");
				tv_status.setText(status);
				break;

			case TAKE_PICTURE:
				startPhotoZoom(tempUri);
				break;

			case CHOOSE_PICTURE:
				Uri uri = data.getData();
				Bitmap bitmap = null;
				String imgPath = null;
				ContentResolver resolver = this.getContentResolver();
				String[] columns = { MediaStore.Images.Media.DATA };
				Cursor cursor = null;
				cursor = resolver.query(uri, columns, null, null, null);
				imgPath = uri.getPath();
				if (!TextUtils.isEmpty(imgPath) && imgPath.contains(":")) {
					String imgIndex = imgPath.split(":")[1];
					cursor = resolver.query(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							columns, "_id=?", new String[] { imgIndex }, null);
				}

				if (null != cursor && cursor.moveToFirst()) {
					int columnIndex = cursor.getColumnIndex(columns[0]);
					imgPath = cursor.getString(columnIndex);
					cursor.close();
					String filePath = imgPath;
				}

				if (!TextUtils.isEmpty(imgPath)) {
					bitmap = genBitmap(imgPath);
					bitmap2headimg = genBitmap(imgPath);
					iv_user_headimg.setImageBitmap(bitmap);
					isPic = "1";
				}
				break;
			case CROP_SMALL_PICTURE:
				if (data != null) {
					setImageToView(data);
				}
				break;
			}
		}
	}

	/**
	 * @param picdata
	 */
	protected void setImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			iv_user_headimg.setImageBitmap(photo);
			try {
				saveFile(photo, jpgName + ".jpg");
			} catch (IOException e) {
				e.printStackTrace();
			}
			isPic = "1";
		}
	}

	/**
	 * 
	 * @param uri
	 */
	protected void startPhotoZoom(Uri uri) {
		if (uri == null) {
			Log.i("tag", "The uri is not exist.");
		}
		tempUri = uri;
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CROP_SMALL_PICTURE);
	}

	/** 通过给定的图片路径生成对应的bitmap */
	private Bitmap genBitmap(String imgPath) {
		Options options = new Options();
		// options.inJustDecodeBounds = true;

		// 将图片像素设置为低像素
		options.inDensity = DisplayMetrics.DENSITY_HIGH;
		// 降低图片质量 设置为16位
		options.inPreferredConfig = Config.ARGB_8888;

		BitmapFactory.decodeFile(imgPath, options);
		int imageWidth = options.outWidth;
		int imageHeight = options.outHeight ;
//		int imageWidth = options.outWidth > 100 ? 100 : options.outWidth;
//		int imageHeight = options.outHeight > 100 ? 100 : options.outHeight;

		
		
		
		int widthSample = (int) (imageWidth / mWH);
		int heightSample = (int) (imageHeight / mWH);
		// 计算缩放比例
		// options.inSampleSize = widthSample < heightSample ? heightSample
		// : widthSample;
		// options.inSampleSize=2;
		if (imageWidth < 2048* 5 || imageHeight < 2048* 5) {
			options.inSampleSize = 1;
		} else if (imageWidth > 2048* 5 || imageHeight > 2048* 5) {
			options.inSampleSize = 1;
		}
		// options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
		bitmap = BitmapCompressor.decodeSampledBitmapFromBitmap(bitmap,
				imageWidth / (options.inSampleSize * 1), imageHeight
						/ (options.inSampleSize * 1));

		try {
			saveFile(bitmap, jpgName + ".jpg");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bitmap;
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		String path = getSDPath() + "/goldupload/";
		File dirFile = new File(path);
		
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}

		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		bos.flush();
		bos.close();
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}

	public void upload() {
		
		ll_loading.setVisibility(ll_loading.VISIBLE);
		
		httpUtils = new HttpUtils();
		url = Constant.servlet_MessageController;
//http://www.moregolden.com/ycsj_jpxgn/servlet/MessageController?type=8&icon=15871695200_0&name=哈哈
//&nickname=哈哈&gender=男&year=2000&month=01&day=01&tel=15871695200&address=湖北-武汉&school=&grade=
//&teamnum=-1&classnum=-1&userID=13006314760&payment=
		
		String[] split1 = birthday.split("-");
		 String year = split1[0];
		 String month = split1[1];
		 String day = split1[2];
		
		params = new RequestParams();
		params.addBodyParameter("type", "8");
		params.addBodyParameter("userID",SPUtil.getString(CreatStudentActivity.this, "account", ""));
		params.addBodyParameter("name",name);
		params.addBodyParameter("nickname", nickname);
		params.addBodyParameter("gender", sex);
		params.addBodyParameter("year", year);
		params.addBodyParameter("month", month);
		params.addBodyParameter("day", day);
		params.addBodyParameter("tel", tel);
		params.addBodyParameter("address", address);
		params.addBodyParameter("school", school);
		params.addBodyParameter("grade", grade);
		params.addBodyParameter("teamnum", "-1");
		params.addBodyParameter("classnum", "-1");
		params.addBodyParameter("payment", payment);
		params.addBodyParameter("icon", jpgName);

//		String path = getSDPath() + "/goldupload/" + pngName + ".png";
//		File f = new File(path);
//		String[] split = path.split("\\/");
//		// String name = split[split.length - 1];
//		String name = pngName + ".png";
//		params.addBodyParameter(name, f, "image/png");
//		params.addBodyParameter("fileinfo", name);

		httpUtils.send(HttpMethod.POST, url, params, callBackHeadimg);
	}

	private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			Gson gson = new Gson();
			// 2 使用gson对象的方法
			AttResponse fromJson = gson.fromJson(json,
					 AttResponse.class);
			 
			 Log.e("test1", json);
			if(fromJson!=null){
				if("1".equals(fromJson.state)){
					
					uploadheadimg();
				}else if("0".equals(fromJson.state)){
					ll_loading.setVisibility(ll_loading.GONE);
					Toast.makeText(CreatStudentActivity.this, "抱歉，该学生已存在，无法被重复创建", 0).show();
				}else{
					ll_loading.setVisibility(ll_loading.GONE);
					Toast.makeText(CreatStudentActivity.this, "抱歉，服务器开小差了", 0).show();
				}
			}
		}

		

		@Override
		public void onFailure(HttpException error, String msg) {
			
			Toast.makeText(CreatStudentActivity.this, "网络无响应，请检查网络连接是否正常", 0).show();
			
		}
	};
	
	
	
	private void uploadheadimg() {
		HttpUtils httpUtils1 = new HttpUtils();
		url = Constant.servlet_MessageController;
		//http://www.moregolden.com/ycsj_jpxgn/servlet/MessageController?type=46&c=15871695200
		//&name=pic.jpg&role=2&platform=2
		params1 = new RequestParams();
		params1.addBodyParameter("type", "46");
		params1.addBodyParameter("c",SPUtil.getString(CreatStudentActivity.this, "account", ""));
		params1.addBodyParameter("name",jpgName+".jpg");
		params1.addBodyParameter("role", role);
		params1.addBodyParameter("platform", "2");

		String path = getSDPath() + "/goldupload/" + jpgName + ".jpg";
		File f = new File(path);
		String[] split = path.split("\\/");
		// String name = split[split.length - 1];
		String name = jpgName + ".jpg";
		
		params1.addBodyParameter(name, f, "image/jpg");
//		params1.addBodyParameter("fileinfo", name);

		httpUtils1.send(HttpMethod.POST, url, params1, callBackHeadimg1);
	}

	
	private RequestCallBack<String> callBackHeadimg1 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			
			Log.e("test2", json);
			
			Gson gson = new Gson();
			
			 AttResponse fromJson = gson.fromJson(json,
					 AttResponse.class);
			 
			if(fromJson!=null){
				
				if("1".equals(fromJson.state)){
					ll_loading.setVisibility(ll_loading.GONE);
					Toast.makeText(CreatStudentActivity.this, "创建成功", 0).show();
					finish();
				}
			}
		}

		

		@Override
		public void onFailure(HttpException error, String msg) {
			Toast.makeText(CreatStudentActivity.this, "网络无响应，请检查网络连接是否正常", 0).show();
		}
	};
	
}









